#include <stdio.h>
#include <string.h>

#ifdef _WIN32
#include <windows.h>
#elif defined(__linux__) || defined(__APPLE__)
#include <unistd.h>
#include <limits.h>
#endif

void getExecutableDir(char *dir, size_t size) {
    char path[4096];

    // Windows
    #ifdef _WIN32
    GetModuleFileName(NULL, path, sizeof(path));
    char *lastSlash = strrchr(path, '\\');
    if (lastSlash) lastSlash = '\0';

    // Linux
    #elif defined (__linux__)
    ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1);
    if (len != -1) {
        path[len] = '\0';
        char *lastSlash = strrchr(path, '/');
        if (lastSlash) *lastSlash = '\0';
    }

    // macOS
    #elif defined(__APPLE__)
    uint32_t bufSize = sizeof(path);
    if (_NSGetExecutablePath(path, &bufSize) == 0) {
        char *lastSlash = strrchr(path, '/');
        if (lastSlash) *lastSlash = '\0';
    }
    #endif

    strncpy(dir, path, size);
}